import { fetchClassify, ClassifyApi } from '@/api/premium/category/classify'
import {
  ClassifyItem,
  ClassifyType,
} from '@/api/premium/category/model/classifyModel'
import { useStore } from '@/store'
import { computed, ref, watch } from 'vue'
import { noClassifyItem } from '../types'

const useSearchClassifyTree = () => {
  const store = useStore()
  const classifyTree = ref<ClassifyItem[]>([])
  const treeSearchValue = ref<string>('')
  const currentClassify = ref<ClassifyItem>(noClassifyItem)
  const expandedKeys = ref<string[]>([])
  const autoExpandParent = ref<boolean>(true)

  /**
   * 拍平数据
   */
  const generateList = (
    data: ClassifyItem[],
    tempList: ClassifyItem[] = []
  ) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i]
      tempList.push(node)
      if (node.childCateGoryList) {
        generateList(node.childCateGoryList, tempList)
      }
    }
    return tempList
  }
  const dataList = computed(() => generateList(classifyTree.value))
  /**
   * 获得指定父分类的id
   */
  const getParentKey = (
    classId: string,
    tree: ClassifyItem[]
  ): string | undefined => {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i]
      if (node.childCateGoryList) {
        if (node.childCateGoryList.some((item) => item.id === classId)) {
          parentKey = node.id
        } else if (getParentKey(classId, node.childCateGoryList)) {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          parentKey = getParentKey(classId, node.childCateGoryList)
        }
      }
    }
    return parentKey
  }
  /**
   * 获得搜索分类获得需要展开的父节点
   */
  const searchClassify = (keyWord: string) => {
    if (keyWord) {
      const expanded: string[] = []
      dataList.value.forEach((item) => {
        if (item.name.includes(keyWord)) {
          const pId = getParentKey(item.id, classifyTree.value)
          if (pId) expanded.push(pId)
        }
      })
      expandedKeys.value = expanded
    }
  }
  watch(treeSearchValue, (value) => {
    searchClassify(value)
  })

  const getClassifyList = async () => {
    const { data } = await fetchClassify()
    if (data.childCateGoryList) {
      classifyTree.value = data.childCateGoryList.filter(
        (child) => child.type === ClassifyType.IMAGE
      )
    }
    classifyTree.value.unshift(noClassifyItem)
  }
  const fetchClassifyLoading = computed(() =>
    store.getters['global/isOpLoading'](ClassifyApi.GET_CLASSIFY_TREE)
  )

  return {
    getClassifyList,
    fetchClassifyLoading,
    classifyTree,
    treeSearchValue,
    currentClassify,
    searchClassify,
    expandedKeys,
    autoExpandParent,
  }
}

export default useSearchClassifyTree
